package com.itservice.uzalarm;

import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


public class Main extends Activity implements OnClickListener,WeeklySettingDialog.OnResultListener{

	private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 
    private final int SET_TIME_HOUR = 0;
    
    /* Setting Data */
    private TimePicker timePicker;
	private int myhour;
    private int myminute;
    private int iweekly;
    private String sweekly;
    private String myfile;
    private String filename;
    private int gameconf;
    
    /* View Data */
    private TextView wtv,mtv;
    private Button bt1,bt2,bt3;
    private CheckBox cb1;
    private WeeklySettingDialog mWeeklySettingDialog = null;
    private String strKey;
    
    private SharedPreferences SubPref = null;
    private SharedPreferences.Editor SubPref_edit = null;
    private ProgressDialog progressDialog = null;
    private Main tmpContext = this;
	private final Handler handler = new Handler();
	
	private String[] str_items2;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        /* Get key from Intent */
        Intent intent = getIntent();
        strKey = intent.getStringExtra("INPUT_KEY");

        /* Load Preference */
        loadPref(strKey);
        
/*------View Setting------*/
        timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(myhour);
        timePicker.setCurrentMinute(myminute);
        /* TextView */
        wtv = (TextView)findViewById(R.id.TextView06);
        wtv.setText(SubPref.getString(Utility.SWEEKLY_CONF_KEY, "NO DATA"));
        mtv = (TextView)findViewById(R.id.TextView07);
        mtv.setText(filename);
        
        /* ImageView */
        ImageView iv1 = new ImageView(this); 
        iv1 = (ImageView)findViewById(R.id.ImageView01);
        iv1.setImageResource(R.drawable.path);
        
        ImageView iv2 = new ImageView(this); 
        iv2 = (ImageView)findViewById(R.id.ImageView02);
        iv2.setImageResource(R.drawable.path);

        ImageView iv3 = new ImageView(this); 
        iv3 = (ImageView)findViewById(R.id.ImageView03);
        iv3.setImageResource(R.drawable.path);
        
        ImageView iv9 = new ImageView(this); 
        iv9 = (ImageView)findViewById(R.id.ImageView09);
        iv9.setImageResource(R.drawable.path);

        /* Button */
        bt1 = (Button)findViewById(R.id.Button01);
        bt1.setOnClickListener(this);

        bt2 = (Button)findViewById(R.id.Button02);
        bt2.setOnClickListener(this);
        
        bt3 = (Button)findViewById(R.id.Button03);
        bt3.setOnClickListener(this);
        
        /* CheckBox */
        cb1 = (CheckBox)findViewById(R.id.maze_math);
        if(gameconf == Utility.GAME_CONF_MAZE)
        {
        	//ゲーム迷路ON
            cb1.setChecked(true);
        }else{
        	//ゲームマス計算ON
            cb1.setChecked(false);
        }
        cb1.setOnClickListener(this);
/*------View Setting------*/

        /* when called? -> PickerChange */
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            	/* ここだけじゃまずい？キーボードからの編集がかかると。。 */
            	myhour = hourOfDay;
            	myminute = minute;
            }
        });
    }

	public void onClick(View v){
		if(v == bt1){
			/* weekly setting */
			showDialog(1);
			
		}else if(v == bt2){
			/* music setting */
			selectFile();
		}else if(v == bt3){
			/* setting end */
			SETButtonEvent();
		}else if(v == cb1){
			if (cb1.isChecked()) {
				cb1.setChecked(true);
				gameconf = Utility.GAME_CONF_MAZE;
			}
			else
			{
				cb1.setChecked(false);
				gameconf = Utility.GAME_CONF_MATH;
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id){
		mWeeklySettingDialog = new WeeklySettingDialog(this);
		mWeeklySettingDialog.setOnResultListener(this);
		return mWeeklySettingDialog;
	}
	
	private void loadPref(String key){
		/* SharedPref setting */
		SubPref = getSharedPreferences(key, Context.MODE_PRIVATE);
		SubPref_edit = SubPref.edit();
		
		/* Load Data */
		myhour = SubPref.getInt(Utility.WAKE_HOUR_KEY, 0);
		myminute = SubPref.getInt(Utility.WAKE_MIN_KEY, 0);
		iweekly = SubPref.getInt(Utility.WEEKLY_CONF_KEY, 0);
		sweekly = SubPref.getString(Utility.SWEEKLY_CONF_KEY, "NO DATA");
		myfile = SubPref.getString(Utility.FILEPATH_KEY, "");
		filename = SubPref.getString(Utility.FILENAME_KEY, "NO DATA");
		gameconf = SubPref.getInt(Utility.GAME_CONF_KEY, 1);
	}
	
    private void SETButtonEvent(){
		/* * *
		 * Error check!!
		 *  All Data input?
		 */
		
    	/* data to String */
    	String WakeTimeHour;
    	if(myhour < 10){
    		WakeTimeHour = "0" + Integer.toString(myhour);
    	}else{
    		WakeTimeHour = Integer.toString(myhour);
    	}
    	String WakeTimeMinute;
    	if(myminute < 10){
    		WakeTimeMinute = "0" + Integer.toString(myminute);
    	}else{
    		WakeTimeMinute = Integer.toString(myminute);
    	}
    	String weeklyData = "";
    	
    	/* Save this Data */
    	SubPref_edit.putInt(Utility.WAKE_HOUR_KEY, myhour);
    	SubPref_edit.putInt(Utility.WAKE_MIN_KEY, myminute);
    	SubPref_edit.putInt(Utility.WEEKLY_CONF_KEY, iweekly);
    	SubPref_edit.putString(Utility.SWEEKLY_CONF_KEY, sweekly);
    	SubPref_edit.putString(Utility.FILEPATH_KEY,myfile);
    	SubPref_edit.putString(Utility.FILENAME_KEY, filename);
    	SubPref_edit.putInt(Utility.GAME_CONF_KEY, gameconf);
       	Log.v("uzalarm","Main gameMode: " + gameconf);

    	SubPref_edit.commit();
    	
		//Return Data
		Intent intent = new Intent();
		intent.putExtra("RET_KEY", strKey);
		intent.setAction(Intent.ACTION_VIEW);
		setResult(RESULT_OK, intent);
		
		finish();
    }
    
    private int key2num(String key){
    	int ret = 0;
    	if(key.equals(Utility.PREF_DATA1_KEY)){
    		ret = 1;
    	}else if(key.equals(Utility.PREF_DATA2_KEY)){
    		ret = 2;
    	}else if(key.equals(Utility.PREF_DATA3_KEY)){
    		ret = 3;
    	}else if(key.equals(Utility.PREF_DATA4_KEY)){
    		ret = 4;
    	}else if(key.equals(Utility.PREF_DATA5_KEY)){
    		ret = 5;
    	}
    	return ret;
    }

	@Override
	public void OnResult(int resultCode, String WeeklyData, int weekcode) {
		wtv.setText(WeeklyData);
		sweekly = WeeklyData;
		iweekly = weekcode;
	}

	private void selectFile()
	{
		progressDialog = new ProgressDialog(this);
	    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    progressDialog.setMessage("Finding Music from SDCARD...");
	    progressDialog.setCancelable(true);
	    progressDialog.show();
	    (new Thread(runnable)).start(); 
	}
	
	private Runnable runnable = new Runnable(){
		@Override
		public void run() {
			//	ファイルの一覧を検索するディレクトリパスを指定する
			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
		    
			//　　ファイルの拡張子の決定、検索したい拡張子を格納する。
			String[] sFileExtension = {"*.(m|M)(p|P)3","*.(m|M)4(a|A)"};
					
			//	選択ボックスで表示するファイル名のリストを作成
			final File[] filelist = FileSearch.listFiles(path,sFileExtension);
			str_items2 = new String[filelist.length];
			for(int i = 0; i < filelist.length; i++){
				str_items2[i] = filelist[i].getName();
			}
			
			handler.post(new Runnable() {
				@Override
				public void run(){
					//	ファイルの選択ボックスを表示
					AlertDialog alertDialog = new AlertDialog.Builder(tmpContext)
					.setTitle("Set Music")
					.setItems(str_items2, new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int which) 
						{
							if (which < filelist.length)
							{
								File filePath = filelist[which];
//								File filePath = files_temp[which];
								Toast.makeText(Main.this, 
									"Set the：「" + filePath + "」 \n Completed!", 
									Toast.LENGTH_LONG).show();
									textSet(mtv,filePath.getPath(),filePath.getName());		
							}
						}
					}
					)
					.create();
					alertDialog.show();	//	Display Menu Show
				}
			});
			
			progressDialog.dismiss();
		}
	};
	

	private void textSet(TextView tmp,String fPath,String fName){
		myfile = fPath;
		filename = fName;
		tmp.setText(fName);
	}

}